<template>
  <template v-if="!!selectedWidget.options.areaDataEnabled" >
    <el-form-item :label="i18nt('designer.setting.areaDataEnabled')">
      <el-switch v-model="optionModel.areaDataEnabled" disabled></el-switch>
    </el-form-item>
  </template>
  <template v-if="blankEditorShowing">
    <div style="display: none" />
  </template>
  <template v-else-if="!selectedWidget.options.areaDataEnabled">
    <el-form-item label-width="0">
      <el-divider class="custom-divider-margin-top">{{i18nt('designer.setting.optionsSetting')}}</el-divider>
    </el-form-item>
    <el-form-item :label="i18nt('designer.setting.labelKeyName')">
      <el-input v-model="optionModel.labelKey"></el-input>
    </el-form-item>
    <el-form-item :label="i18nt('designer.setting.valueKeyName')">
      <el-input v-model="optionModel.valueKey"></el-input>
    </el-form-item>
    <el-form-item label="数据字典">
      <el-select v-model="optionModel.dictType" filterable clearable @change="getOptions">
        <el-option v-for="(item, idx) in dictList" :key="idx" :title="item.description"
                   :label="item.description" :value="item.dictType"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="hasConfig('childrenKey')" :label="i18nt('designer.setting.childrenKeyName')">
      <el-input v-model="optionModel.childrenKey"></el-input>
    </el-form-item>
    <el-form-item :label="i18nt('designer.setting.dsEnabled')" v-if="!optionModel.dictType">
      <el-switch v-model="optionModel.dsEnabled"></el-switch>
    </el-form-item>
    <el-form-item v-if="!!optionModel.dsEnabled" :label="i18nt('designer.setting.dsName')">
      <el-select v-model="optionModel.dsName" filterable clearable @change="getDataSetList">
        <el-option v-for="(item, idx) in dataSourceList" :key="idx" :title="item.description"
                   :label="item.uniqueName" :value="item.uniqueName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="!!optionModel.dsEnabled" :label="i18nt('designer.setting.dataSetName')">
      <el-select v-model="optionModel.dataSetName" filterable clearable>
        <el-option v-for="(item, idx) in dataSetList" :key="idx" :title="item.remark"
                   :label="item.name" :value="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="!!optionModel.dsEnabled" :label="i18nt('designer.setting.firstOptionAsDefault')">
      <el-switch v-model="optionModel.firstOptionAsDefault"></el-switch>
    </el-form-item>
    <el-form-item v-if="!optionModel.dsEnabled" label-width="0">
      <option-items-setting :designer="designer" :selected-widget="selectedWidget" v-loading="optionsLoading"></option-items-setting>
    </el-form-item>
  </template>
</template>

<script>
  import i18n from "@/utils/i18n"
  import OptionItemsSetting from "@/components/form-designer/setting-panel/option-items-setting"
  import propertyMixin from "@/components/form-designer/setting-panel/property-editor/propertyMixin";
  import {getDSByName} from "@/utils/util"
  import { getDictListAPI, getDicts } from "@/api/dict/dict"

  export default {
    name: "optionItems-editor",
    mixins: [i18n, propertyMixin],
    props: {
      designer: Object,
      selectedWidget: Object,
      optionModel: Object,
    },
    components: {
      OptionItemsSetting,
    },
    data() {
      return {
        dataSetList: [],
        dictList: [],
        optionsLoading: false,
      }
    },
    computed: {
      dataSourceList() {
        if (!this.designer.formConfig || !this.designer.formConfig.dataSources) {
          return []
        } else {
          return this.designer.formConfig.dataSources
        }
      },

      blankEditorShowing() {
        return !window.advancedDevMode && this.selectedWidget.optionItemsReadonly
      },

    },
    watch: {
      selectedWidget: {
        handler(val, oldVal) {
          if (!val) {
            return
          }

          this.loadDataSet(val.options.dsName)
        },
        immediate: true
      },

    },
    mounted(){
      this.getDictList()
    },
    methods: {
      loadDataSet(dsName) {
        this.dataSetList.length = 0
        if (!dsName) {
          return
        }

        let dsModel = getDSByName(this.designer.formConfig, dsName)
        if (!!dsModel && !!dsModel.dataSets) {
          dsModel.dataSets.forEach(dSet => {
            this.dataSetList.push({
              name: dSet.name,
              remark: dSet.remark
            })
          })
        }
      },

      getDataSetList() {
        this.optionModel.dataSetName = ''
        this.loadDataSet(this.optionModel.dsName)
      },
      /**
       * 获取数据字典项
       */
      getDictList() {
        getDictListAPI().then(res => {
          this.dictList = res.data
        }).catch(err => {
          this.$message.error(err.msg)
        })
      },
      /**
       * 根据字典项获取数据字典值
       * @param {*} type 字典项
       */
      async getOptions(type) {
        this.optionsLoading = true
        await getDicts(type).then( res => {
          const list = res.data
          this.optionModel.optionItems = list
          // 使用变量存储中间结果，提高可读性
          const isCheckboxOrMultiple = this.selectedWidget.type === "checkbox" || this.selectedWidget.options.multiple || this.selectedWidget.type === 'checkbox-with-input';
          const hasListAndItems = list && list.length > 0;
          const firstItemValue = list?.[0]?.value;
          // 根据条件设置默认值
          let defaultValue;
          if (isCheckboxOrMultiple) {
            defaultValue = hasListAndItems ? [firstItemValue] : [];
          } else {
            defaultValue = hasListAndItems ? firstItemValue : "";
          }
          this.optionModel.defaultValue = defaultValue
          this.emitFormModelChange(defaultValue)
        })
        this.optionModel.dsEnabled = false
        this.optionModel.dsName = ''
        this.optionModel.dataSetName = ''
        this.optionsLoading = false
      },
    }
  }
</script>

<style scoped>

</style>
